package edu.njfu.controller;

import edu.njfu.pojo.Borrower;
import edu.njfu.pojo.Borrowing;
import edu.njfu.service.IBorrowerService;
import edu.njfu.service.IBorrowingService;
import edu.njfu.util.AdminException;
import edu.njfu.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/borrowing")
public class BorrowingController {

    @Autowired
    private IBorrowingService borrowingService;

    @GetMapping("/list")
    public Result list() {
        try {
            List<Borrowing> list = borrowingService.findAll();
            return new Result("查询成功", list);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/findByStatus")
    public Result findByStatus(@RequestParam Integer status) {
        try {
            List<Borrowing> list = borrowingService.findByStatus(status);
            return new Result("查询成功", list);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/lostBook")
    public Result findByStatus(@RequestParam Long id) {
        try {
            borrowingService.lostBook(id);
            return new Result("上报丢失/损坏成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestParam String borrowerName,
                               @RequestParam String borrowingName) {
        try {
            borrowingService.save(borrowerName,borrowingName);
            return new Result("保存成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/returnBook")
    public Result returnBook(@RequestParam Long id) {
        try {
            borrowingService.returnBook(id);
            return new Result("归还成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

}
